<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Hash;
use DB;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Requests\UserFromPostRequest;


class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function getIndex(Request $request)
    {
        $users = DB::table('users')->paginate(5);
      return view('Admin.user.index',['users'=>$users]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function getAdd()
    {
        return view('Admin.user.add');
    }
    

    public function postInsert(UserFromPostRequest $request)
    {
 
        $data = $request->except('_token');
            $data['pic'] = $this->upload($request);
         // if($request->hasfile('password')){
            $data['password'] = Hash::make($data['password']);

            $res = DB::table('users')->insert($data);
            if($res)
            {
                return redirect('admin/user/index')->with('success','添加成功');
            }else
            {
                 return back()->with('error','用户添加失败啦');
            }

       
    }

    public function upload(Request $request)
    {

            // dd($request->hasFile('pic'));
           //检测是否有文件上传
        if ($request->hasFile('pic')) {
            //随机文件名
            $name = md5(time()+rand(1,99999));
            //后缀名
            $su = $request->file('pic')->getClientOriginalExtension();
            $request->file('pic')->move('public/uploads/',$name.'.'.$su);
            return '/public/uploads/'.$name.'.'.$su;
        }

    }

    public function postDel(Request $request)
    {
        $id = $request->input('id');

        $res = DB::table('users')->where('id',$id)->delete();

        if($res)
        {
            echo 1;
        }else{
            echo 0;
        }
    }
    public function getEdit($id)
    {
        $users = DB::table('users')->where('id',$id)->first();
        return view('Admin.user.edit',['users'=>$users]);
    }

   public function postUpdate(Request $request)
    {
        $data = $request->except('_token');
        // dd($data);

         if ($request->hasFile('pic')) {
             //调用方法进行头像的上传操作
             $data['pic'] = $this->upload($request);
         }
        

        //执行数据修改
         $res = DB::table('users')->where('id',$data['id'])->update($data);
        if($res){
            //重定向到 user/index
            return redirect('admin/user/index')->with('success','用户修改成功');
        }else{
            //回到上个页面
            return back()->with('error','用户修改失败啦');
        }

    }
}
